from flask import Flask, request, session, render_template, jsonify, redirect
import subprocess
from collections import Counter
import datetime
import json
import math
import os
import re
import pandas as pd
import re
import ast
import shutil
from time import sleep

import test_socket

import detection,alarm_association,alarm_convergence

app = Flask(__name__)
app.secret_key = "6666"
app.config['UPLOAD_FOLDER'] = 'flask/uploads/'

import sys
current_dir = os.path.dirname(os.path.abspath(__file__))
tts_assistant_dir = os.path.join(current_dir, '..', 'TTS_Assistant')
sys.path.append(tts_assistant_dir)

try:
    from Socket_TTS import *
except:
    pass


current_dir = os.path.dirname(os.path.abspath(__file__))
tts_assistant_dir = os.path.join(current_dir, '..', 'smart')
sys.path.append(tts_assistant_dir)

try:
    from bot import *
except:
    pass


from alipay import AliPay


#默认每次使用功能扣一毛钱。现在为了调试方便暂时允许负数余额。
def do_payment(money_2_pay = 0.1):
    BASE_DIR = os.path.abspath(os.path.dirname(__file__))
    with open(os.path.join(BASE_DIR, "user.json"), "r", encoding="utf-8") as f:
        users = json.load(f)
    now_user = session["username"]
    users[now_user]["credit"] -= money_2_pay
    with open(os.path.join(BASE_DIR, "user.json"), "w", encoding="utf-8") as f:
        json.dump(users, f)


@app.route("/", methods=["GET", "POST"])
def index():
    return render_template("login.html")


# 处理登录和注册请求
@app.route("/user", methods=["POST"])
def user():
    BASE_DIR = os.path.abspath(os.path.dirname(__file__))

    user_json_path = os.path.join(BASE_DIR, "user.json")
    if not os.path.exists(user_json_path):
        # 创建目录和文件
        os.makedirs(BASE_DIR, exist_ok=True)
        with open(user_json_path, "w", encoding="utf-8") as f:
            json.dump({}, f)
    # 读取user.json文件
    with open(os.path.join(BASE_DIR, "user.json"), "r", encoding="utf-8") as f:
        users = json.load(f)

    # 获取表单数据
    username = request.form.get("username")
    password = request.form.get("password")

    # 判断请求类型
    if request.form.get("type") == "login":
        # 登录操作
        if username in users and users[username]["password"] == password:
            session["username"] = username
            user_credit = users[username]["credit"]
            msg_ = "登录成功, 您的账户余额为：" + str(user_credit)
            
            return jsonify({"status": 1, "msg": msg_})
        else:
            return jsonify({"status": 0, "msg": "用户名或密码错误"})

    elif request.form.get("type") == "register":
        # 注册操作
        if username not in users:
            # 创建新用户
            users[username] = {"password": password, "history": [], "credit": 0}
            # 更新user.json文件
            with open(os.path.join(BASE_DIR, "user.json"), "w", encoding="utf-8") as f:
                json.dump(users, f)
            return jsonify({"status": 1, "msg": "注册成功"})
        else:
            return jsonify({"status": 0, "msg": "用户名已存在"})


def parse_anomal_detection_output(output, op_name):
    do_payment()
    if op_name == 'anomal_detection':
        lines = output.split('\n')
        result_dict = {}
        model_results = []

        current_model = None
        for line in lines:
            if line.startswith('model:'):
                if current_model:
                    model_results.append(current_model)
                current_model = {'model': line.split(':')[1].strip()}
            elif 'check result' in line and 'percent' in line:
                parts = line.split(',')
                for part in parts:
                    key, value = part.split(':', 1)
                    current_model[key.strip()] = value.strip()
            elif line.startswith('final result:'):
                result_dict['final_result'] = line.split(':')[1].strip()

        if current_model:
            model_results.append(current_model)
        result_dict['model_results'] = model_results
        return result_dict

    else:
        return output


# 渲染上传文件页面
@app.route('/upload_file_form', methods=['GET'])
def upload_file_form():
    return render_template('upload_file.html')

# 处理文件上传
@app.route('/upload', methods=['POST','GET'])
def upload():
    if request.method == 'POST':
        if 'file' not in request.files:
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            return redirect(request.url)
        if file and (file.filename.endswith('.csv') or file.filename.endswith('.txt')):
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
            file.save(filepath)

            # 根据文件类型进行不同的处理
            if file.filename.endswith('.csv'):
                # 读取CSV文件
                data = pd.read_csv(filepath)
                print(data.head())
            elif file.filename.endswith('.txt'):
                # 读取TXT文件
                with open(filepath, 'r') as f:
                    data = f.read()
                print(data)
            return render_template('upload_success.html')
       # 如果是 GET 请求或者文件类型不支持，返回上传页面
    return render_template('upload_file.html')
        

# @app.route('/upload_file', methods=['GET', 'POST'])
# def upload_file():
#     if request.method == 'POST':
#         if 'file' not in request.files:
#             return redirect(request.url)
#         file = request.files['file']
#         if file.filename == '':
#             return redirect(request.url)
#         if file and (file.filename.endswith('.csv') or file.filename.endswith('.txt')):
#             filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
#             file.save(filepath)

#             # 根据文件类型进行不同的处理
#             if file.filename.endswith('.csv'):
#                 # 读取CSV文件
#                 data = pd.read_csv(filepath)
#                 print(data.head())
#             elif file.filename.endswith('.txt'):
#                 # 读取TXT文件
#                 with open(filepath, 'r') as f:
#                     data = f.read()
#                 print(data)

#         #test_socket.fuck()
#         #TODO
#         ##
#         #这个地方就已经是读取到data了，所以接下来可以直接处理数据然后返回给temp_show_result。
#         #这里目前暂时只是简单的展示结果。
#         # 检查用户点击了哪个按钮
#         action = request.form.get('action')
#         # if action == 'upload':
#         #     return render_template('upload_file_results.html', filename=file.filename)

#         # output = {}
#         # error = {}
#         # commands = [
#         #     ('anomal_detection', [
#         #         'python', 'flask/detection.py',
#         #         '--data_dir=' + filepath,
#         #         '--period_freq=D',
#         #         '--voting_num=3'
#         #     ]),
#         #     ('alarm_association', [
#         #         'python', 'flask/alarm_convergence.py',
#         #         '--data_dir=' + filepath,
#         #         '--minsupport=0.2',
#         #         '--minconf=0.5'
#         #     ]),
#         #     ('ts_predict', [
#         #         'python', 'flask/ts_period_predict.py',
#         #         '--model_name=lr',
#         #         '--data_dir=./aiopstools/timeseries_predict/data/timeseries_data.csv',
#         #         '--predict_time=24'
#         #     ])
#         # ]

#         # for op_name, command in commands:
#         #     try:
#         #         result = subprocess.run(command, capture_output=True, text=True, check=True)
#         #         output[op_name] = parse_anomal_detection_output(result.stdout, op_name)
#         #         error[op_name] = result.stderr
#         #     except subprocess.CalledProcessError as e:
#         #         output[op_name] = f"An error occurred: {e.stderr}"
#         #         error[op_name] = None
#         # print(output.keys())
#         if action == 'anomal_detection':
#             # 执行异常检测命令
#             command = [
#                 'python', 'flask/detection.py',
#                 '--data_dir=' + filepath,
#                 '--period_freq=D',
#                 '--voting_num=3'
#             ]
#             template='anomal_detection.html'

#             op_name = 'anomal_detection'
#             output = {}
#             error = {}
#             try:
#                 result = subprocess.run(command, capture_output=True, text=True, check=True)
#                 output[op_name] = parse_anomal_detection_output(result.stdout, op_name)
#                 error[op_name] = result.stderr
#             except subprocess.CalledProcessError as e:
#                 output[op_name] = f"An error occurred: {e.stderr}"
#                 error[op_name] = None

#             summary_output = '  '
#             for op_name, result in output.items():
#                 model_results_text = [
#                     f"模型{model_result['model']}的预测检查是{model_result['check result']}，预测异常概率是{model_result['percent']}%"
#                     for model_result in result['model_results']
#                 ]

#                 final_judge = "无异常" if result['final_result'] == 'anticlimax' else "有异常"
#                 summary_output += (
#                     f"在整体投票中，{'；'.join(model_results_text)}，。" + 
#                     "最终投票结果为，您当前的运维情况" + final_judge + "。"
#                 )

                    
#             return render_template(template, filename=file.filename, output=output,error=error, summary_text = summary_output)
        
        
#         elif action == 'alarm_association':
#             # 执行警报关联分析命令
#             command = [
#                 'python', 'flask/alarm_convergence.py',
#                 '--data_dir=' + filepath,
#                 '--minsupport=0.2',
#                 '--minconf=0.5'
#             ]
#             template='alarm_association.html'
#         elif action == 'ts_predict':
#             # 执行时间序列预测命令
#             command = [
#                 'python', 'flask/ts_period_predict.py',
#                 '--model_name=lr',
#                 '--data_dir=./aiopstools/timeseries_predict/data/timeseries_data.csv',
#                 '--predict_time=24'
#             ]
#             template='ts_predict_result.html'
#             pattern = r"the prediction result:\s*(\[.*?\])"

#             result = subprocess.run(command, capture_output=True, text=True, check=True)
#             # 打印输出结果进行调试
#             print(result.stdout)
#             output=result.stdout
#             error=None
            
#             match = re.search(pattern, output, re.DOTALL)
            
#             if match:
#                 prediction_result_str = match.group(1)
#                 prediction_results = ast.literal_eval(prediction_result_str)
#             else:
#                 prediction_results = []
#             #print(prediction_results)
#             return render_template(template, filename=file.filename, output=output, error=error, prediction_results=prediction_results)
#         # else:
#         #     # 处理未知操作的情况，例如日志记录或返回错误页面
#         #     return render_template('error.html', message='Unknown action: ' + action)

#         # try:
#         #     # 执行命令并捕获输出
            
#         # except subprocess.CalledProcessError as e:
#         #             output = f"An error occurred: {e.stderr}"
#         #             error = None

#         # 渲染结果页面并传递输出结果
#         return render_template(template, filename=file.filename, output=output,error=error)

            
#     else:
#         return 'Invalid file format. Please upload a CSV file.'

## funtion 
@app.route('/detection', methods=['GET', 'POST'])
def detection():
    do_payment()
    if request.method == 'POST':
        if 'file' not in request.files:
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            return redirect(request.url)
        if file and (file.filename.endswith('.csv') or file.filename.endswith('.txt')):
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
            file.save(filepath)

            # 根据文件类型进行不同的处理
            if file.filename.endswith('.csv'):
                # 读取CSV文件
                data = pd.read_csv(filepath)
                print(data.head())
            elif file.filename.endswith('.txt'):
                # 读取TXT文件
                with open(filepath, 'r') as f:
                    data = f.read()
                print(data)

        # Perform time series prediction using the uploaded file

            command = [
                'python3', 'flask/detection.py',
                '--data_dir=' + filepath,
                '--period_freq=D',
                '--voting_num=3'
            ]
            template='anomal_detection.html'
            
            op_name = 'anomal_detection'
            output = {}
            error = {}
            try:
                print(command)
                result = subprocess.run(command, capture_output=True, text=True, check=True)
                output[op_name] = parse_anomal_detection_output(result.stdout, op_name)
                error[op_name] = result.stderr
            except subprocess.CalledProcessError as e:
                output[op_name] = f"An error occurred: {e.stderr}"
                error[op_name] = None
                return render_template('error.html')

            summary_output = '  '
            for op_name, result in output.items():
                model_results_text = [
                    f"模型{model_result['model']}的预测检查是{model_result['check result']}，预测异常概率是{model_result['percent']}%"
                    for model_result in result['model_results']
                ]

                final_judge = "无异常" if result['final_result'] == 'anticlimax' else "有异常"
                summary_output += (
                    f"在整体投票中，{'；'.join(model_results_text)}，。" + 
                    "最终投票结果为，您当前的运维情况" + final_judge + "。"
                )

                    
            return render_template(template, filename=file.filename, output=output,error=error, summary_text = summary_output)
        
    
    # If it's a GET request, simply render the upload form
    return render_template('confirm_anomal_detection.html')








@app.route('/ts_pre', methods=['GET', 'POST'])
def ts_pre():
    do_payment()
    if request.method == 'POST':
        if 'file' not in request.files:
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            return redirect(request.url)
        if file and (file.filename.endswith('.csv') or file.filename.endswith('.txt')):
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
            file.save(filepath)

        # 根据文件类型进行不同的处理
        try:
            if file.filename.endswith('.csv'):
                # 读取CSV文件
                data = pd.read_csv(filepath)
                # 仅保留'value'列
                original_data = data['value'].tolist()
            elif file.filename.endswith('.txt'):
                # 读取TXT文件
                with open(filepath, 'r') as f:
                    original_data = [float(line.strip().split(',')[1]) for line in f]  # 假设TXT文件每行格式为 timestamp, value
            else:
                original_data = None
        except Exception as e:
            return render_template('error.html')
        
        # print(original_data)
        # 获取预测时间
        predict_time = request.form.get('predict_time', 24)  # 默认值为24
        try:
            predict_time = int(predict_time)
        except ValueError:
            predict_time = 24  # 如果转换失败，使用默认值24

        # 执行时间序列预测
        command = [
            'python', os.path.join('flask', 'ts_period_predict.py'),  # 确保使用了正确的路径
            '--model_name=lr',
            f'--data_dir={filepath}',  # 使用上传的文件作为输入
            f'--predict_time={predict_time}'
        ]
        try:
            print(command)
            result = subprocess.run(command, capture_output=True, text=True, check=True)
            print("after subprocess")
            output = result.stdout
            error = result.stderr

            pattern = r"the prediction result:\s*(\[.*?\])"
            match = re.search(pattern, output, re.DOTALL)
            if match:
                prediction_result_str = match.group(1)
                prediction_results = ast.literal_eval(prediction_result_str)
            else:
                prediction_results = []
            print(prediction_results)
            return render_template('ts_predict_result.html', output=output, error=error, prediction_results=prediction_results, original_data=original_data)

        except subprocess.CalledProcessError as e:
            print("Command failed with error: ", e.stderr)
            return render_template('error.html')
    
    # If it's a GET request, simply render the upload form
    return render_template('confirm_ts_predict.html')



def parse_alarm_conv_output(output):
    do_payment()
    rules = []
    lines = output.strip().split('\n')
    for line in lines:
        parts = line.split(' --> ')
        antecedent = parts[0].replace("frozenset(", "").replace(")", "").replace("{", "").replace("}", "").strip()
        consequent_conf = parts[1].split(' conf: ')
        consequent = consequent_conf[0].replace("frozenset(", "").replace(")", "").replace("{", "").replace("}", "").strip()
        confidence = float(consequent_conf[1].strip())
        rules.append({'antecedent': antecedent, 'consequent': consequent, 'confidence': confidence})
    return rules


@app.route('/alarm_convergence', methods=['GET', 'POST'])
def alarm_convergence():
    do_payment()
    if request.method == 'POST':
        if 'file' not in request.files:
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            return redirect(request.url)
        if file and (file.filename.endswith('.csv') or file.filename.endswith('.txt')):
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
            file.save(filepath)

            # 根据文件类型进行不同的处理
            try:
                if file.filename.endswith('.csv'):
                    # 读取CSV文件
                    data = pd.read_csv(filepath)
                    print(data.head())
                elif file.filename.endswith('.txt'):
                    # 读取TXT文件
                    with open(filepath, 'r') as f:
                        data = f.read()
                    # print(data)
            except Exception as e:
                return render_template('error.html')

        # 获取参数
        min_support = request.form.get('min_support', 0.2)  # 默认值为0.2
        try:
            min_support = float(min_support)
        except ValueError:
            min_support = 0.2  # 如果转换失败，使用默认值0.2

        min_conf = request.form.get('min_conf', 0.5)  # 默认值为0.5
        try:
            min_conf = float(min_conf)
        except ValueError:
            min_conf = 0.5  # 如果转换失败，使用默认值0.5

        # 执行
        command = [
            'python', os.path.join('flask', 'alarm_convergence.py'),  # 确保使用了正确的路径
            f'--data_dir={filepath}',  # 使用上传的文件作为输入
            f'--minsupport={min_support}',
            f'--minconf={min_conf}'
        ]
        try:
            print(command)
            result = subprocess.run(command, capture_output=True, text=True, check=True)
            print("after subprocess")
            output = result.stdout
            error = result.stderr
            # 处理脚本输出
            print("Script output:", output)
            if error:
                print("Script error:", error)

            # 解析输出
            rules = parse_alarm_conv_output(output)
            # 渲染模板
            return render_template('alarm_convergence_result.html', rules=rules)
        
        except subprocess.CalledProcessError as e:
            print("Command failed with error: ", e.stderr)
            return render_template('error.html')
    
    # If it's a GET request, simply render the upload form
    return render_template('confirm_alarm_convergence.html')




@app.route('/alarm_association', methods=['GET', 'POST'])
def alarm_association():
    do_payment()
    if request.method == 'POST':
        # 处理host.alive文件
        if 'host_file' not in request.files:
            return redirect(request.url)
        host_file = request.files['host_file']
        if host_file.filename == '':
            return redirect(request.url)
        host_filepath = os.path.join(app.config['UPLOAD_FOLDER'], host_file.filename)
        host_file.save(host_filepath)
        
        # 处理监控项名和相关文件
        item_names = request.form.getlist('item_name[]')
        alldata_files = request.files.getlist('alldata_file[]')
        alarm_data_files = request.files.getlist('alarm_data_file[]')

        # 创建一个列表，存储每个监控项及其对应的文件
        monitoring_data = []

        for i in range(len(item_names)):
            print(i)
            item_name = item_names[i]
            alldata_file = alldata_files[i]
            alarm_data_file = alarm_data_files[i]

            # 保存上传的文件
            if alldata_file and alarm_data_file:
                alldata_filepath = os.path.join(app.config['UPLOAD_FOLDER'], alldata_file.filename)
                alarm_data_filepath = os.path.join(app.config['UPLOAD_FOLDER'], alarm_data_file.filename)
                alldata_file.save(alldata_filepath)
                alarm_data_file.save(alarm_data_filepath)

                # 将监控项名及其文件路径添加到列表中
                monitoring_data.append({
                    'item_name': item_name,
                    'alldata_file': alldata_filepath,
                    'alarm_data_file': alarm_data_filepath
                })


        # 调用子进程运行具体的处理函数
        command = [
            'python', os.path.join('flask', 'alarm_association.py'),  # 确保使用了正确的路径
            f'--host_file={host_filepath}',
            f'--monitoring_data={monitoring_data}'
        ]
        try:
            print(command)
            result = subprocess.run(command, capture_output=True, text=True, check=True)
            output = result.stdout
            error = result.stderr
            print(output)
            # 处理脚本输出
            print("Script output:", output)
            if error:
                print("Script error:", error)
            # 渲染模板
            # 解析脚本输出为字典
            output_data = ast.literal_eval(output.strip())

            # 渲染模板
            return render_template('alarm_association_result.html', output_data=output_data)

        except subprocess.CalledProcessError as e:
            print("Command failed with error: ", e.stderr)
            return render_template('error.html')
    
    # If it's a GET request, simply render the upload form
    return render_template('confirm_alarm_association.html')


@app.route('/log_analysis_count', methods=['GET', 'POST'])
def log_analysis_count():
    do_payment()
    if request.method == 'POST':
        if 'file' not in request.files:
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            return redirect(request.url)
        if file and (file.filename.endswith('.csv') or file.filename.endswith('.txt')):
            filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
            file.save(filepath)

            # 根据文件类型进行不同的处理
            if file.filename.endswith('.csv'):
                # 读取CSV文件
                data = pd.read_csv(filepath)
                # print(data.head())
            elif file.filename.endswith('.txt'):
                # 读取TXT文件
                with open(filepath, 'r') as f:
                    data = f.read()
                # print(data)

        # 执行
        command = [
            'python', os.path.join('flask', 'log_analysis_count.py'),  # 确保使用了正确的路径
            f'--data_dir={filepath}'  # 使用上传的文件作为输入
        ]
        try:
            print(command)
            result = subprocess.run(command, capture_output=True, text=True, check=True)
            print("after subprocess")
            output = result.stdout
            error = result.stderr
            # 处理脚本输出
            print("Script output:", output)
            if error:
                print("Script error:", error)
            output = result.stdout.strip().split("\n")

            log_entries = []
            for line in output:
                parts = line.split(" ", 1)
                count = int(parts[0].strip(":"))
                message = parts[1].strip()
                log_entries.append({"count": count, "message": message})

            return render_template('log_analysis_count_result.html', log_entries=log_entries)
            # 解析输出
            # rules = parse_alarm_conv_output(output)
            # 渲染模板
            # return render_template('log_analysis_count_result.html', rules=rules)
        
        except subprocess.CalledProcessError as e:
            print("Command failed with error: ", e.stderr)
            # return jsonify({'error': e.stderr})
            return render_template('error.html')
    
    # If it's a GET request, simply render the upload form
    return render_template('confirm_log_analysis_count.html')


@app.route('/render_ts_predict')
def render_ts_predict():
    do_payment()
    output = request.args.get('output')
    error = request.args.get('error')
    prediction_results = request.args.get('prediction_results')
    return render_template('ts_predict_result.html', output=output, error=error, prediction_results=prediction_results)
# @app.route('/index_page')
# def index_page():

#     return render_template('index_page.html')


@app.route('/index_page')
def index_page():
    return render_template('index_page.html')


public = """-----BEGIN PUBLIC KEY-----
            MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4O4T63+/HaTFz213+i/Kppq4Mzk0OER4KxJdaIL3sE/Ng7aKNjqN73xPH87mQD+raht0onS3ro4kkMsMS3MzVKhjPtg3ZawzqO+QfCBBg+T7pNLZQNEAvw/f3t57WAoszt8rixp7ZiwavRKxZEBxwinH1qx1LnG1GK6UYwamP/3H0i9AdyfeCh7lRw2PeeR9DcIyE3/PNkrusy5GRlu9fkOHRk6WKb9wqyr2x9Uk6utiNLIRTkjGJiHSJtqXoBXPhM4dLOO6hK/KzIs3V08leUUZh+AxGMwV3rz1yDI9ZoE80nRmS8MZQ+6n+/ayQ1eVYkIJsAnv03P44g8Uec7VtwIDAQAB
            -----END PUBLIC KEY-----
        """
private = """-----BEGIN RSA PRIVATE KEY-----
            MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCdMqkJRvnYslUGU5wSP9tTtQiLCVRnpTD3SsOPZQBjWPqmgbKJEm//+TzRt3TTh37WF2F8vpmu7RQqTRQwQBiKqKnuD7EkJ6F9sDWQxc55DJYgHsSWMhIGMRLUEquNT/kuYE+rLCFTW5D6UmA5AmhmclrvLzpwm5nJ1bjQoV9CCM2/yfcZS/DpIYoNhl/CLb3wZnvD0s3OAiy76+lgIZGgWKLkKwjN2OZPd5IGtXhAIh/foMq0aOZVgh6HPPLRNwDYkkImcgkAR1oQYazqhFs9Y/qXW0Aq1GtuvNB32WrK/IQBbPlyWCWXm6iGvuk0u+xKseqm52UkRrA742oaF42VAgMBAAECggEAdhiAG0MiImTfMXCQuLkWec1wTJvGuFLG9ZFKV6jmYLyRGZQoX4flcmV5BoiPkPajGA3apE/Av0TGuHzNpO4SQeEyQHGzf9jyHq3JoCiq1A/bnOfggoG9Pr+RSJd6ICCrr+aVE6CErM4GnbhTJ6Eic4yHulc9zSlooNQaE0qYeM9cSTkgBfEGrUf7L+hfwN05jSO2R4NJPJpXFGNodDjSbuz8RAyTn/oKYyU0UlQtFebPAnJ7VHEiUAAZE8zlGo86ME6gVmnuAdbXzOHrkjFRBCN+Y14hkMGZd2gUMsna+kMKK3orqkzCNO1lBSE1FLCPyDatOZ1xshN8dFe1M7HHBQKBgQDWQdSN9PVPEZjAwcUQR8HPh+4NtxoqAaNum8aHar5W6SD5hHOZgjly/KY3/uHjqrfyirHkh3Qa+4L0jQGjVeAzPGjp/4U9m7xR3O2DW5j7/8B7BZroNCpqRMfwb2i6/4/6rOm2z0TVP0s9izYvB180KjG6pWtRoCU3pcj/gC4rzwKBgQC70vlxvIjGAigmck07cW6DZ5Mh8qcnsNXgYbMPltJocnN/QIvJQ/3csQUsVt4U0zTwdueO+sCLmWCNG4OgWRvTcO2dHQ9ejTxOtqvPkFboebTaCCnLzL094l3DN72AO9PsD88sTBsDAiow6UWm5ICxR8KataKjw78PwPup1goVWwKBgQCd/kdGMvddygURRxIREkkJxxu1A2uIxFKG8tnv67fWEO1e8dvovA2vDD1qF0rtfmtMsBfEBFqKtyL3QK+PiXjdb1OSEfln19qDp12But7SHOMMFLMJPcZ1PKkPVKgvFNtQJ4fkZW1FrvnFtU1MWqxKpD6teuPreiNXqKnSNuxVIwKBgDumv449wHqSiMndF2Y/mkelh3cKp8fVQ7flj4bt8Zk2cDQD/eFH9MI4flocpJ+cjH2qZdRlEu3DIoTuLhmo80tt3Ck/53eyB2tAXMSpJNDkhmmQmiWduqSC1iB//XFSjvWz96or6ZBFCb1K+NIOVEj5b3bPJP451t5b/hFsZvttAoGALe3ugtNMbsqXfyZ0SGgRhiYh89hBSqdChqmMPaePPJveD11NSyU4hD6OD8Kb3aTv598FTDhMfhHc77bqGGtdUphD2bmPDo4+3kDV6J0jdns3cK0QiBSJPGNkKCb4GSRVhUX2pdEKfPmq+8dTwaUfGlM3ptadU9+4aNYyWYh+iO8=
            -----END RSA PRIVATE KEY-----
        """

alipay_config = {
    'app_id': '9021000138683855',
    'app_private_key_string': open('flask/private.pem').read(),
    'alipay_public_key_string': open('flask/public.pem').read(),
    'sign_type': 'RSA2',
    'debug': True,
}
# 初始化Alipay实例
alipay = AliPay(
    appid=alipay_config['app_id'],

    app_private_key_string=alipay_config['app_private_key_string'],
    alipay_public_key_string=alipay_config['alipay_public_key_string'],
    sign_type=alipay_config['sign_type'],
    debug=alipay_config['debug']
)



@app.route('/add_cash')
def add_cash():
    return render_template('add_cash.html')

def generate_order_id():
    return random.randint(1000000000000000, 9999999999999999)  # 生成一个16位的随机数

@app.route('/pay', methods=['POST', 'GET'])
def pay():
    # 获取前端传来的订单信息
    order_id = generate_order_id() #request.args.get('order_id')
    #subject = request.args.get('subject')
    subject = "充值会员"
    #total_amount = request.form.get('data-price')
    package = request.args.get('total_amount')#['package']
    
    package_prices = {
        'gold': 128,
        'diamond': 258,
        'platinum': 648,
        'test':0.01
    }
    total_amount = package_prices[package]

    order_url = alipay.api_alipay_trade_page_pay(
        subject = subject,    #订单项目名
        out_trade_no = order_id,   #订单号
        total_amount = total_amount,   #订单价格
        return_url = 'http://119.3.188.118:5001/return_url',
	)
    pay_url  = "https://openapi-sandbox.dl.alipaydev.com/gateway.do?{query_params}".format(query_params=order_url)
    
    #return pay_url
    return redirect(pay_url)
    #print(order_url)
    #return order_url

    # 从结果中获取支付链接
    #alipay_url = order_result.get('qr_code')  # 注意：这里应该是 code_url 而不是 qr_code

    # 返回支付链接
    return jsonify({"alipay_url": alipay_url})
    

@app.route('/credit_check', methods=['POST', 'GET'])
def credit_check():
    BASE_DIR = os.path.abspath(os.path.dirname(__file__))
    with open(os.path.join(BASE_DIR, "user.json"), "r", encoding="utf-8") as f:
        users = json.load(f)
    now_user = session['username']
    discribe = "亲爱的" + now_user + ", 您当前的余额为" + str(users[now_user]["credit"])
    return render_template('credit_check.html', discribe = discribe)

    


@app.route('/return_url', methods=['GET'])
def return_handler():
    # 从GET请求中获取支付宝返回的参数
    params = request.args.to_dict()
    #print(params)

    # 访问参数
    trade_no = params.get('trade_no')
    out_trade_no = params.get('out_trade_no')
    total_amount = params.get('total_amount')

    BASE_DIR = os.path.abspath(os.path.dirname(__file__))
    with open(os.path.join(BASE_DIR, "user.json"), "r", encoding="utf-8") as f:
        users = json.load(f)
    now_user = session['username']

    if 'processed_orders' not in session:
        session['processed_orders'] = []
        session.modified = True

    
    #print("\n",trade_no, session['processed_orders'],"\n")
    

    #print("\n\n", session['processed_orders'])
    if trade_no in session['processed_orders']:
        trade_status = "订单已处理, 您现在的余额是" + str(users[now_user]["credit"]) + "元"
    else:
        users[now_user]["credit"] += float(total_amount)
        trade_status = "亲爱的" + now_user + ", 您现在的余额是" + str(users[now_user]["credit"]) + "元"
        # 更新数据库中的订单状态
        with open(os.path.join(BASE_DIR, "user.json"), "w", encoding="utf-8") as f:
            json.dump(users, f)
        session['processed_orders'].append(trade_no)
        session.modified = True

       
    #print(session['processed_orders'], "\n\n",)
    
    # 渲染一个页面给用户，显示支付结果
    return render_template('payment_result.html', trade_status=trade_status, **params)

@app.route('/intro')
def intro():
    return render_template('intro.html')


@app.route('/about')
def about():
    return render_template('about.html')


@app.route('/main_new')
def main_new():

    return render_template('main_new.html')



@app.route('/smart_qa')
def smart_qa():
    return render_template('smart_QA.html')


handler = ChatBotGraph()
def generate_bot_response(user_message):
    question = user_message
    answer = handler.chat_main(question)
    
    return answer


@app.route('/smart_qa_result', methods=['GET'])
def smart_qa_result():
    file_path = 'check.py'
    code = ''
    if os.path.exists(file_path):
        with open(file_path, 'r', encoding='utf-8') as f:
            code = f.read()
    return render_template('smart_qa_result.html', code=code)



@app.route('/get', methods=['GET'])
def get_response():
    #一条token扣一毛
    do_payment()
    # 获取从前端发送过来的 msg 参数
    user_message = request.args.get('msg')

    # 在这里编写处理用户消息并生成机器人回复的代码
    bot_response = generate_bot_response(user_message)
    bot_speech_url = None
    bot_speech = None
    try:
        wav_name = 'jesus.wav'
        bot_speech = gen_wave(bot_response, wav_name)

        shutil.copy(bot_speech, './flask/static')
        bot_speech_url = './static/' + wav_name
    except:
        pass

    response_data = {
        'bot_response': bot_response, 
        #'bot_speech':bot_speech
        'bot_speech':bot_speech_url
    }

    return jsonify(response_data)


@app.route('/personal_info')
def personal_info():
    BASE_DIR = os.path.abspath(os.path.dirname(__file__))
    with open(os.path.join(BASE_DIR, "user.json"), "r", encoding="utf-8") as f:
        users = json.load(f)
    now_user = session['username']

    info = "您好，" + now_user + ", 您的余额是" + str(users[now_user]["credit"])

    return render_template('personal_info.html', info = info)


@app.route('/main')
def main():

    return render_template('main.html')


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5001,debug=True)